package com.lefeee.paperrec;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import static java.net.HttpURLConnection.HTTP_OK;

/**
 * Created by cw on 2018/6/3.
 */

public class NetCall {
    private String TAG = "cw_net";
    private String SITE = "http://www.2lou.net:5000/todo/api/v1/";
    private HttpURLConnection connection = null;

    public NetCall() {

    }

    //1. Test Get User
    String getUser() {
        String target = "user";
        return exc_get(target);
    }

    private String exc_get(String target) {

        int req_code;
        try {
            URL url = new URL(SITE + target);
            connection = (HttpURLConnection) url.openConnection();

            connection.setDoOutput(false);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");

            connection.setRequestProperty("Content-length", "0");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(2 * 1000);
            connection.setReadTimeout(2 * 1000);

            req_code = connection.getResponseCode();

            Log.d(TAG, "url: " + url.toString());

            Log.d(TAG, "rec: " + req_code);

            if (HTTP_OK == req_code) {
                StringBuffer stringBuffer = new StringBuffer();
                String readline;
                BufferedReader bufferedReader;
                bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((readline = bufferedReader.readLine()) != null) {
                    stringBuffer.append(readline).append("\n");
                }
                bufferedReader.close();
                return stringBuffer.toString();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private String exc_post(String target) {
        String result = null;

        try {
            URL url = new URL(SITE + target);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            connection = (HttpURLConnection) url.openConnection();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

}
